package com.gitee.gen.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Date;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.gitee.gen.auto.sql.AutoTableScriptGenerator;
import com.gitee.gen.auto.sql.AutoTableXlsxUtils;
import com.gitee.gen.common.Action;
import com.gitee.gen.common.Result;

import cn.hutool.core.date.DateUtil;


@RestController
public class AutoSqlController {

	private static final Logger logger = LoggerFactory.getLogger(AutoSqlController.class);

	
    /**
     * todo 文件上传
     * @param response
     * @param file
     */
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    public Result uploadFile(HttpServletResponse response, MultipartFile file) {
    	InputStream xlsx = null;
    	OutputStream out = null;
		try {
			xlsx = file.getInputStream();
			if(xlsx==null) {
	    		return Action.err("文件为空");
	    	}
			XSSFWorkbook workbook = AutoTableXlsxUtils.getXSSFWorkbook(xlsx);
			String sqlScript = AutoTableScriptGenerator.geneateScript(AutoTableXlsxUtils.getTableScript(workbook), "gen.sql");
			if(sqlScript!=null) {
				// 放行Content-disposition响应头
				response.setHeader("Access-Control-Expose-Headers", "Content-disposition");
				response.setHeader("Content-Disposition", "attachment;filename="+ 
						URLEncoder.encode(("gen_" + DateUtil.format(new Date(), "yyyyMMddHHmm") + ".sql"), "UTF-8"));
				out = response.getOutputStream();
		        out.write(sqlScript.getBytes());
				return Action.ok();
			}else {
				logger.info("uploadFile geneateScript");
			}
		} catch (IOException e) {
			logger.error("uploadFile", e);
		}finally {
			if(xlsx!=null) {
				try {
					xlsx.close();
				} catch (IOException e) {
				}
			}
			
			if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                }
            }
		}
        return Action.err("上传文件失败");
    }

}
